<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="JavaScript笔试刷题小结（二）, Casey Lu&#39;s Blog">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>JavaScript笔试刷题小结（二） | Casey Lu&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/medias/maozhao.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/atom.xml" title="Casey Lu's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Casey Lu's Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Casey Lu's Blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('嘻嘻嘻，访问本文章需要密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误哦~');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/articleimages/5.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">JavaScript笔试刷题小结（二）</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Javascript/">
                                <span class="chip bg-color">Javascript</span>
                            </a>
                        
                            <a href="/tags/Leetcode/">
                                <span class="chip bg-color">Leetcode</span>
                            </a>
                        
                            <a href="/tags/%E7%AE%97%E6%B3%95/">
                                <span class="chip bg-color">算法</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%AC%94%E8%AF%95%E9%9D%A2%E8%AF%95/" class="post-category">
                                笔试面试
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2020-03-10
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    1.2k
                </div>
                

                

                
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>继续整理最近的刷题记录<img class="emoji" draggable="false" alt="📝" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4dd.png"/></p>
<h2 id="1-剑指Offer-39-数组中出现次数过半的数字"><strong>1. 剑指Offer 39. 数组中出现次数过半的数字</strong></h2>
<p>书中提到了两种复杂度均为O(n)的解法：<br>
1）基于<strong>Partition</strong>函数：<br>
如果这个数字存在，那它必然是数组排序后的中位数，基于随机快排中的Partition的思想对数组进行操作，如果选中的数字index = n/2，恰好它是中位数；index&gt;n/2,中位数在其左边；index&lt;n/2,中位数在其右边<br>
cc觉得js可以如此简单粗暴：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var majorityElement = function(nums){
  nums.sort()
  return nums[Math.floor(nums.length/2)]
}
</code></pre>
<p><img src="https://img-blog.csdnimg.cn/20200307184939478.png" alt="leetcode执行结果"><br>
2）根据<strong>数组特点</strong>：<br>
如果该数字存在，则它的次数绝对比其他元素多;<br>
遍历数组，同时统计当前元素的次数，出现相同元素+1，出现其他元素-1，最后返回times&gt;0的元素，即为所求数字</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var marjorityElement = function(nums){
  let res = nums[0]
  let times = 1
  for(let i = 1; i < nums.length; ++i){
    if(times === 0){
      res = nums[i]
      times = 1
    }else if(nums[i] === res){
      times ++
    }else{
      times --
    }
  }
  return res
}
</code></pre>
<p><img src="https://img-blog.csdnimg.cn/20200307200201330.png" alt="leetcode执行结果"></p>
<h2 id="2-剑指Offer-59-Ⅱ-队列中的最大值"><strong>2. 剑指Offer 59-Ⅱ. 队列中的最大值</strong></h2>
<p>这个题目，要不是出现在每日挑战，我真的不会做，出题人思路清奇？尤其是看了评论区发现大家都看不懂，得~~~没有技术含量，尤其对于js和python来说</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var MaxQueue = function() {
    this.arr = []
};

/**
 * @return {number}
 */
MaxQueue.prototype.max_value = function() {
    return (this.arr.length > 0) ? Math.max(...this.arr) : -1
};

/** 
 * @param {number} value
 * @return {void}
 */
MaxQueue.prototype.push_back = function(value) {
  if(value !== null){
    this.arr.push(value)
  }
};

/**
 * @return {number}
 */
MaxQueue.prototype.pop_front = function() {
    if(this.arr.length > 0)
      return this.arr.shift()
    return -1
};
</code></pre>
<h2 id="3-剑指Offer-42-连续子数组的最大和"><strong>3. 剑指Offer 42. 连续子数组的最大和</strong></h2>
<p>使用动态规划计算，当前位置处的最大和等于上一个位置上的最大和与与最大和加当前位置值之和中的较大值，状态转移方程式：<br>
<img src="https://img-blog.csdnimg.cn/20200307201331275.png" alt="状态转移方程"></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var maxSubArray = function(nums) {
    let res = nums[0]
    let maxSum = 0
    nums.map((item) =>{
        maxSum = Math.max(maxSum + item, item)
        res = Math.max(maxSum, res)
    })
    return res
};
</code></pre>
<h2 id="4-剑指Offer-40-最小的k个函数"><strong>4. 剑指Offer 40. 最小的k个函数</strong></h2>
<p>对于js和python来说，这道题调包当然非常简单，截取排序数组的前k个即可</p>
<p>1）<strong>直接排序做法</strong>（简单、直观、时间O(n*logN) ---- 空间O(logN)）：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var getLeastNumbers = function(arr, k){
  return arr.sort((a,b) => a-b).slice(0,k)
}
</code></pre>
<p>但是实际上，我们获取前k个数字的时候，并不需要对整个数组进行排序，尤其是在 k &lt;&lt; length 的情况下，是非常消耗性能的</p>
<p>2） <strong>使用最大堆</strong>（手动写堆略复杂、时间O(K) ---- 空间O(n*logK)）</p>
<p>整体的算法流程：</p>
<ul>
<li>创建大小为k的最大堆</li>
<li>将数组的前k个元素放入堆中</li>
<li>从下标k继续开始依次遍历数组的剩余元素<br>
（如果元素小于堆顶元素，那么取出堆顶元素，将当前元素入堆；如果元素大于/等于堆顶元素，不做操作）</li>
</ul>
<pre class=" language-language-javascript"><code class="language-language-javascript">function swap(arr, i, j){
  [arr[i], arr[j]] = [arr[j], arr[i]]
}
class maxHeap{
  constructor(arr = []){
    this.container == []
    if(Array.isArray(arr)){
      arr.forEach(this.insert.bind(this))
    }
  }

  insert(data){
    const {container} = this
    container.push(data)
    let index = container.length - 1
    while(index){
      let parent = Math.floor((index-1)/2)
      if(container[index] <= container[parent]){
        break
      }
      swap(container, index, parent)
      index = parent
    }
  }
  extract(){
    const { container } = this
    if(!container.length){
      return null
    }
    swap(container, 0, container.length-1)
    const res = container.pop()
    const length = container.length
    let index = 0
    let exchange = index * 2 + 1
    while(exchange < length){
      let right = index * 2 + 2
      if(right < length && container[right] > container[exchange]){
        exchange = right
      }
      if(container[exchange] <= container[index]){
        break
      }
      swap(container, exchange, index)
      index = exchange
      exchange = index * 2 + 1
    }
    return res
  }
  top(){
    if(this.container.length){
      return this.container[0]
    }
    return null
  }
}
var getLeastNumbers = function(arr, k){
  const length =  arr.length
  if(k >= length){
    return arr
  }
  const heap = new MaxHeap(arr.slice(0,k))
  for(let i = k; i < length; ++i){
    if(hash.top() > arr[i]){
      heap.extract()
      heap.insert(arr[i])
    }
  }
  return heap.container
}
</code></pre>
<p>3）<strong>基于快速排序的Partition</strong>（时间O(N) ---- 空间O(N)）：</p>
<p>可以使用快速排序中的Partition,把元素arr[0]放入排序后的正确位置，并且返回这个位置index。算法流程如下：</p>
<ul>
<li>如果index = k, 说明第k个元素已经放在正确位置，返回前k个</li>
<li>如果index &gt; k,前k个元素在[left, index-1]之间，缩小查找范围，继续查找</li>
<li>如果index &lt; k,前k个元素在[index+1,right]之间，缩小查找范围，继续查找</li>
</ul>
<pre class=" language-language-javascript"><code class="language-language-javascript">function partition(arr, start, end){
  const k = arr[start]
  let left = start + 1
  let right = end
  while(1){
    while(left <= end && arr[left] <= k) ++ left
    while(right >= start && arr[right] >= k) -- right

    if(left >= right){
      break
    }
    [arr[right], arr[start]] = [arr[start], arr[right]]
    return right
  }
}
var getLeastNumbers = function(arr, k){
  const length = arr.length
  if(k >= length) return arr
  let left = 0
  let right = length - 1
  let index = partition(arr, left, right)
  while(index !== k){
    if(index < k){
      left = index + 1
    }else if(index > k){
      right = index - 1
    }
    index = partition(arr, left, right)
  }
  return arr.slice(0,k)
}
</code></pre>
<p>相比之下，更推荐第三种Partition的解法，手写堆太复杂了</p>
<h2 id="5-⭐️-Leetcode-93-复原IP地址"><strong>5. <img class="emoji" draggable="false" alt="⭐️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2b50.png"/> Leetcode 93. 复原IP地址</strong></h2>
<p>思路：使用基于递归的DFS方法，去掉不符合的情况，每次从字符串开始位置截掉长度为1，2，3之后剩下的子串，用于递归<br>
关于这个题，求助了Z同学<img class="emoji" draggable="false" alt="🐷" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f437.png"/>，开始思路有点乱<img class="emoji" draggable="false" alt="💫" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4ab.png"/><img class="emoji" draggable="false" alt="💫" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4ab.png"/><img class="emoji" draggable="false" alt="💫" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4ab.png"/>然后茅塞顿开<br>
定义递归函数很重要，思路就是每次切完当前的串之后，继续切后面的串，所以在递归函数中，我把变量设置为剩下的串，</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var restoreIpAddresses = function(s){
  let res = []
  // 首先判断s长度是否满足ip，标准IP地址的长度范围4~12 (0.0.0.0 ~ 255.255.255.255)
  if(s.length < 4 || s.length > 12)   return res
   // cur表示当前未划分的字符串，pre表示前面已经划分好的（加上.的），counts表示已经划分的段数（pre中.的个数）
  function divideIpAddress(cur, pre, counts){
    if(counts === 3){
	  // 如果已经到了第三段了，只需要检查剩下的串
	  if(cur.length <= 3 && parseInt(cur.slice(0,3)) < 256 ){
	    if(cur.length >= 2 && cur.charAt(0)==='0'){
	      return //说明第四段里面首位是0，绝对不可能再划分了，剪枝
	    }
	    // 否则，将当前剩余的字符串加入到分段队列，ip分段成功
	    let item = pre.concat(cur)
	    res.push(item)
	  }
   }
   if(counts < 3){
     // 划分长度为1的作为一段
     let item = pre.concat(cur.slice(0,1)).concat('.')
     divideIpAddress(cur.slice(1), item, counts+1)
     if(cur.charAt(0) !== '0'){
       // 首位不是0的情况下，划分长度为2的作为一段
       item = pre.concat(cur.slice(0,2)).concat('.')
       divideIpAddress(cur.slice(2), item, counts+1)
       if(parseInt(cur.slice(0,3)) < 256){
         // 首位不是0且数值小于256的情况下，划分长度为3的作为一段
         item = pre.concat(cur.slice(0,3)).concat('.')
         divideIpAddress(cur.slice(3), item, counts+1)
       }
     }
   }
  }
  divideIpAddress(s, "", 0)
  return res
}
</code></pre>
<p>tips: 1）注意开头是0的情况 2）提前添加长度的判断（标准ip长度在4~12）</p>
<h2 id="6-Leetcode-121-买卖股票的最佳时机"><strong>6. Leetcode 121.买卖股票的最佳时机</strong></h2>
<p>思路：遍历一遍数组，记录今天之前的最低价格，和今天卖出的利润，更新最大利润，时间复杂度O(n),空间复杂度O（1）</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var maxProfit = function(prices) {    
  let minP = prices[0]    
  let maxP = 0    
  prices.map((item)=>{        
    maxP = item - minP > maxP? item - minP : maxP        
    if(item < minP){            
      minP = item        
    }    
  })    
  if(maxP > 0){        
    return maxP    
  }    
  return 0
};
</code></pre>
<h2 id="7-Leetcode-543-二叉树的直径"><strong>7. Leetcode 543.二叉树的直径</strong></h2>
<p>思路：遍历树，比较每个节点的左右子树的高度之和，记录最大的长度为树的直径(最初cc只考虑了根节点，导致忽略了最长直径不一定过根节点，虽然题目没有指明，但是一定要考虑到）</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var diameterOfBinaryTree = function(root){
  let diameter = 0
  const getMaxDepth = node =>{
    if(!node){
      return -1
    }
    let left = getMaxDepth(node.left)
    let right = getMaxDepth(node.right)
    diameter = Math.max(diameter,left+right+2) // 更新最大值
    return Math.max(left,right)+1 // 返回当前节点下的最大深度
  }
}
</code></pre>
<h2 id="8-Leetcode-112-路径总和"><strong>8. Leetcode 112.路径总和</strong></h2>
<p>思路：总之，递归大法好</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var hasPathSum = function(root, sum) {
    if(root === null){
        return false
    }
     if(root.left === null && root.right === null){
        if(root.val === sum){
            return true
        }
        return false
    }
    return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val)
};
</code></pre>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io" rel="external nofollow noreferrer">Casey Lu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io/2020/03/10/9-javascript-bi-shi-shua-ti-xiao-jie-er/">https://caseylu.gitee.io/2020/03/10/9-javascript-bi-shi-shua-ti-xiao-jie-er/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Javascript/">
                                    <span class="chip bg-color">Javascript</span>
                                </a>
                            
                                <a href="/tags/Leetcode/">
                                    <span class="chip bg-color">Leetcode</span>
                                </a>
                            
                                <a href="/tags/%E7%AE%97%E6%B3%95/">
                                    <span class="chip bg-color">算法</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">谢谢大佬的小鱼干，喵~</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b739596984975414aa79',
        clientSecret: 'c5792bc3376f951910111f232176fbadfa919286',
        repo: 'L0ittle.github.io',
        owner: 'L0ittle',
        admin: "L0ittle",
        id: '2020-03-10T14-57-03',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2020/03/10/10-javascript-zhong-de-bi-bao-closure/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/38.jpg" class="responsive-img" alt="Javascript中的闭包Closure">
                        
                        <span class="card-title">Javascript中的闭包Closure</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            对JS中的闭包还没有了解过的可看 MDN 闭包， 在面试的时候闭包也是经常被提及的Topic
一、闭包的概念
简单的说，闭包就是有权访问其他函数作用域内部变量的函数
闭包 = 函数 + 函数能够访问的自由变量
闭包的三个特点：

函数嵌套函
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-10
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                    技术分享
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Javascript/">
                        <span class="chip bg-color">Javascript</span>
                    </a>
                    
                    <a href="/tags/%E9%97%AD%E5%8C%85/">
                        <span class="chip bg-color">闭包</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/03/09/8-es6-de-ji-chu-yu-fa-xin-te-xing/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/23.jpg" class="responsive-img" alt="ES6的基础语法新特性">
                        
                        <span class="card-title">ES6的基础语法新特性</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            ES6语法在面试中是频繁被提及的，相比于ES3和ES5它具备许多特性，接下来，主要通过对比将从多个方面逐个介绍它的新特性。
一、常量定义
在ES3中不存在常量的定义，ES5中可以实现，但并未明确的定义，通过对象添加属性prototype实现
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-09
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                    技术分享
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Javascript/">
                        <span class="chip bg-color">Javascript</span>
                    </a>
                    
                    <a href="/tags/ES6/">
                        <span class="chip bg-color">ES6</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('100')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + 'From: Casey Lu&#39;s Blog<br />'
            + 'Author: Casey Lu<br />'
            + 'Link: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="4892766072"
                   fixed='true'
                   autoplay='false'
                   theme:='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">63.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/L0ittle" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:caseylu119@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1351238945" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1351238945" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
